package com.duoec.dw.lineage.service.impl.desc;

import com.duoec.dw.lineage.dto.TableDescItem;
import com.duoec.dw.lineage.dto.TableDescReaderState;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;

/**
 * @author xuwenzhen
 */
@Service
public class DetailTableDescTypeProcessor extends BaseTableDescTypeProcessor {
    public static final String TYPE = "detail";
    private static final String STR_TABLE_PARAMETERS = "Table Parameters:";

    /**
     * 需要处理的type类型
     *
     * @return type类型
     */
    @Override
    public String getType() {
        return TYPE;
    }

    /**
     * 处理一行数据
     *
     * @param state 当前的状态
     * @param rs    当前记录
     * @return 当行数据解析出来的TableDescItem实例
     */
    @Override
    public TableDescItem process(TableDescReaderState state, ResultSet rs) {
        String colName = getColValue(rs, STR_COL_NAME);
        if (StringUtils.isEmpty(colName) && StringUtils.isEmpty(state.getSubType())) {
            return null;
        }

        if (colName.startsWith(STR_TABLE_PARAMETERS)) {
            state.setSubType(SUB_TYPE_STR);
            return null;
        }
        String colValue = getColValue(rs, STR_DATA_TYPE);
        if (!StringUtils.isEmpty(state.getSubType())) {
            if (colValue == null || STR_NULL.equals(colValue)) {
                return null;
            }
            colName = state.getSubType() + DOT + colValue;
            TableDescItem item = new TableDescItem();
            item.setColumnName(colName.trim());
            item.setDataType(getColValue(rs, STR_COMMENT));
            item.setComment(null);
            item.setType(TYPE);
            return item;
        } else {
            TableDescItem item = new TableDescItem();
            item.setColumnName(colName.trim());
            item.setDataType(colValue);
            item.setComment(getColValue(rs, STR_COMMENT));
            item.setType(TYPE);
            return item;
        }
    }
}
